//
//  ListViewController.m
//  Project two framework
//
//  Created by 张峥 on 16/7/21.
//  Copyright © 2016年 张峥. All rights reserved.
//

#import "ListViewController.h"
#import "ListTableViewCell.h"
#import "ZPZNetRequest+getClientList.h"
#import "OtherListTableViewCell.h"
#import "ListView.h"
#import "LUtilityTools.h"
#import "SingleView.h"
#import "ShoprDataSource.h"
@interface ListViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UIScrollView *scrollView;
/** 第一页 */
@property (nonatomic, strong) UIImageView *backgroundImage;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *name;
/** 订单号 */
@property (nonatomic, strong) UILabel *orderID;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSString *Cid;
@property (nonatomic, strong) UILabel *successID;
/** 第二页 */
@property (nonatomic, strong) UIImageView *otherImage;
@property (nonatomic, strong) UILabel *otherOrderID;
@property (nonatomic, strong) UILabel *otherName;
@property (nonatomic, strong) UILabel *phone;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) UIView *otherLine;
@property (nonatomic, strong) UIButton *submit;


@property (nonatomic, strong) NSString *string;
@property (nonatomic, strong) UIView  *listView;
@property (nonatomic, strong) UIImageView *successImage;
@property (nonatomic, strong) NSString *ID;


@end
static NSInteger indexZ = 0;
@implementation ListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.scrollView];
    [self loadDataSource];
    [self.scrollView addSubview:self.backgroundImage];
    [self.scrollView addSubview:self.successImage];
    [self.successImage addSubview:self.successID];
    [self.backgroundImage addSubview:self.imageView];
    [self.imageView addSubview:self.name];
    [self.imageView addSubview:self.orderID];
    [self.imageView addSubview:self.tableView];
    
    [self.scrollView addSubview:self.otherImage];
    [self.otherImage addSubview:self.otherTableView];
    [self.otherImage addSubview:self.otherOrderID];
    [self.otherImage addSubview:self.otherName];
    [self.otherImage addSubview:self.phone];
    [self.otherImage addSubview:self.otherLine];
    [self.otherImage addSubview:self.addBtn];
    [self.otherImage addSubview:self.submit];
    
    [self.scrollView addSubview:self.listView];
    
    /** 接收购买弹出框 刷新的通知 */
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveRefresh:) name:@"refreshDataSource" object:nil];
    
}

#pragma mark - 第一页网络数据的处理
- (void)loadDataSource
{
    _dataSource = [NSMutableArray array];
    [ZPZNetRequest getClientListPageNum:@"1" PageSize:@"100" UserId:@"22" comletion:^(id object, BOOL success) {
        if (success) {
            [_dataSource addObjectsFromArray:object[@"content"]];
            [_tableView reloadData];

        }
    }];
    
}

#pragma mark - 第二页的网络数据处理
- (void)loadOtherDataSource
{
    _otherDataSource = [NSMutableArray array];
    _otherArray = [NSMutableDictionary dictionary];
    [ZPZNetRequest getClientDetailId:self.Cid comletion:^(id object, BOOL success) {
        if (success) {
            [_otherArray addEntriesFromDictionary:object[@"content"]];
            [_otherDataSource addObjectsFromArray:object[@"content"][@"productList"]];
            [SingleView shareValue].dataSourceArray = [NSMutableArray arrayWithArray:_otherDataSource];
            [_otherTableView reloadData];
        }
    }];
}

#pragma mark - 第二页数据数据刷新的处理
- (void)receiveRefresh:(NSNotification *)info
{
    NSInteger contZ = 0;
//    indexZ= 0;
    NSString *name = _dataSource[indexZ][@"product"][@"name"];
    for (NSDictionary *dic in _otherDataSource) {
        NSString *nameStr = dic[@"product"][@"name"];
        if ([name isEqualToString:nameStr]) {

            
            NSString *string = [NSString stringWithFormat:@"%ld",[_otherDataSource[indexZ][@"purchase_num"] integerValue] + [info.userInfo[@"purchase_num"] integerValue]];
            [dic setValue:string forKey:@"purchase_num"];
            [_otherDataSource replaceObjectAtIndex:indexZ withObject:dic];
            
            
            [_otherTableView reloadData];
            contZ = 1;
        }
        indexZ = indexZ + 1;
    }
    
    
    if (contZ == 0) {
        [_otherDataSource addObject:info.userInfo];
        [SingleView shareValue].dataSourceArray = [NSMutableArray arrayWithArray:_otherDataSource];
        [_otherTableView reloadData];
    }
}



#pragma mark - 提交订单的网络请求
- (void)getsubmitOrderId
{
    [ZPZNetRequest getsubmitOrderId:self.ID Name:self.otherName.text Tel:self.phone.text Status:@"01" UserId:@"22" AmountList:@[self.string] ShoppingList:@[self.otherOrderID.text] comletion:^(id object, BOOL success) {
        if (success) {
            [UIView animateWithDuration:1 animations:^{
                [_scrollView setContentOffset:CGPointMake(0, 0)];
                self.successImage.frame = CGRectMake(80, 80, 625, 400);
            } completion:nil];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:1 animations:^{
                    self.successImage.frame = CGRectMake(80, 80 + SCREEN_HEIGHT, 625, 400);
                }];
            });
        } else {
            [LUtilityTools showAlertWithTitle:@"提交订单失败" message:@"" otherTitle:@"请检查网络" target:self];
        }
    }];
}

#pragma mark - 按钮的实现
/** 提交办理跳转到第二页面 */
- (void)handleAction:(UIButton *)sender
{
    _Cid = _dataSource[sender.tag][@"id"];
    _scrollView.scrollEnabled = YES;
    [UIView animateWithDuration:1 animations:^{
        [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0)];
        [self loadOtherDataSource];
    }];
    

}
/** 添加按钮 */
- (void)addBtnAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        _otherImage.alpha = 0.4;
        self.listView.hidden = NO;
    }else{
        _otherImage.alpha = 1.0;
        self.listView.hidden = YES;
    }
}
/** 提交办理 */
- (void)submitAction:(UIButton *)sender
{
    _successID.text = _otherOrderID.text;
    if (_otherDataSource.count == 0) {
        [LUtilityTools showAlertWithTitle:@"订单不能为空" message:@"" otherTitle:@"确定" target:self ];
    }else {
        [self getsubmitOrderId];
    }
}
/** 删除按钮 */
- (void)cancelAction:(UIButton *)sender
{
    NSIndexPath *indexPath = [self.otherTableView indexPathForCell:(OtherListTableViewCell *)[[sender superview] superview]];
    if (sender.selected) {
        [_otherDataSource removeObjectAtIndex:indexPath.row];
        [_otherTableView reloadData];
    }
    sender.selected = !sender.selected;
    
}

/** 关闭手势 */
- (void)closeTheAddBtn
{
    self.otherImage.alpha = 1;
    self.listView.hidden = YES;
}


#pragma maek -- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (_scrollView.contentOffset.x == 0) {
        _scrollView.scrollEnabled = NO;
    }

}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tableView) {
        return _dataSource.count;
    } else {
        return _otherDataSource.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView) {
        static NSString *indentifier = @"cell";
        ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
        
        if (!cell) {
            cell = [[ListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.handle addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.handle.tag = indexPath.row;
        if (![_dataSource[indexPath.row][@"purchaser"]isKindOfClass:[NSNull class]]) {
            cell.name.text = _dataSource[indexPath.row][@"purchaser"];
        }
            cell.productID.text = _dataSource[indexPath.row][@"order"];

        return cell;
        
    } else {
        static NSString *indentifier = @"cell";
        OtherListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
        if (!cell) {
            cell = [[OtherListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = _otherDataSource[indexPath.row][@"product"];
        _otherOrderID.text = [NSString stringWithFormat:@"订单号: %@",_otherArray[@"order"]];
        _otherName.text = [NSString stringWithFormat:@"姓名: %@",_otherArray[@"purchaser"]];
        _phone.text = [NSString stringWithFormat:@"联系电话: %@",_otherArray[@"telephone"]];
         cell.project.text = dic[@"name"];
        NSString *name = dic[@"categoryName"];
        NSString *str = @"预期收益率(%): ";
        if ([name isEqualToString:@"贵金属"]) {
            cell.number.text = [NSString stringWithFormat:@"%@(个)",_otherDataSource[indexPath.row][@"purchase_num"]];
            cell.content.text = [NSString stringWithFormat:@"橙色: %@, 发行量: %@, 供应商: %@, 规格: %@, 类别: %@, 适宜人群(按年龄段): %@",dic[@"scale"],dic[@"circulation"],dic[@"supplierName"],dic[@"quality"],dic[@"typeName"],dic[@"ageName"]];
        }
        if ([name isEqualToString:@"理财产品"]) {
            cell.number.text = [NSString stringWithFormat:@"%@(万元)",_otherDataSource[indexPath.row][@"purchase_num"]];
            NSNumber *num = dic[@"iternetbank"];
            NSString *strin = [NSString stringWithFormat:@"%@",num];
            
            if ([strin isEqualToString:@"0"]) {
                cell.content.text = [NSString stringWithFormat:@"投资期限(天): %@, %@%@, 起点金额: %@, 起售日: %@, 停售日: %@, 起息日: %@, 到期日: %@, 额度(亿元): %@, 是否支持网银: 不支持",dic[@"deadline"],str,dic[@"product_yield"],dic[@"start_sum"],dic[@"start_time"],dic[@"stop_time"],dic[@"carry_interest"],dic[@"expire_time"],dic[@"product_limit"]];
            } else {
                cell.content.text = [NSString stringWithFormat:@"投资期限(天): %@, %@%@, 起点金额: %@, 起售日: %@, 停售日: %@, 起息日: %@, 到期日: %@, 额度(亿元): %@, 是否支持网银: 支持",dic[@"deadline"],str,dic[@"product_yield"],dic[@"start_sum"],dic[@"start_time"],dic[@"stop_time"],dic[@"carry_interest"],dic[@"expire_time"],dic[@"product_limit"]];
            }
        }
        if ([name isEqualToString:@"基金"]) {
            cell.number.text = [NSString stringWithFormat:@"%@(万元)",_otherDataSource[indexPath.row][@"purchase_num"]];
            cell.content.text = [NSString stringWithFormat:@"单位净值: %@,累计净值: %@,截止日期: %@",dic[@"asset_value"],dic[@"accumulative_value"],dic[@"stop_time"]];
        }
        if ([name isEqualToString:@"出国留学金融服务"]) {
            cell.number.text = [NSString stringWithFormat:@"%@(万元)",_otherDataSource[indexPath.row][@"purchase_num"]];
            cell.content.text = dic[@"abroadInfo"];
        }
        self.string = _otherDataSource[indexPath.row][@"purchase_num"];
        self.ID = _dataSource[indexPath.row][@"id"];
        [cell.cancel addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
}

#pragma mark -  懒加载

- (UIScrollView *)scrollView{
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
        _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, SCREEN_HEIGHT - 80);
        _scrollView.scrollEnabled = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
    }
    return _scrollView;
}


- (UIImageView *)backgroundImage
{
    if (_backgroundImage == nil) {
        _backgroundImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 2, SCREEN_HEIGHT - 80)];
        _backgroundImage.userInteractionEnabled = YES;
        _backgroundImage.image = [UIImage imageNamed:@"背景.png"];
    }
    return _backgroundImage;
}

-(UIImageView *)imageView
{
    if (_imageView == nil) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH - 120, SCREEN_HEIGHT - 120)];
        _imageView.userInteractionEnabled = YES;
        _imageView.image = [UIImage imageNamed:@"down_05.png"];
    }
    return _imageView;
}

- (UILabel *)name
{
    if (_name == nil) {
        _name = [[UILabel alloc]initWithFrame:CGRectMake(30, 30, 200, 25)];
        _name.text = @"姓名";
        _name.textAlignment = NSTextAlignmentCenter;
        _name.textColor = [UIColor whiteColor];
        _name.font = [UIFont systemFontOfSize:25];
    }
    return _name;
}

- (UILabel *)orderID
{
    if (_orderID == nil) {
        _orderID = [[UILabel alloc]initWithFrame:CGRectMake(385, 30, 200, 25)];
        _orderID.text = @"订单号";
        _orderID.textAlignment = NSTextAlignmentCenter;
        _orderID.textColor = [UIColor whiteColor];
        _orderID.font = [UIFont systemFontOfSize:25];
        
    }
    return _orderID;
}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(35, 80, CGRectGetWidth(self.imageView.bounds) - 70, 500)];
        _tableView.rowHeight = 95;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (UIImageView *)successImage
{
    if (_successImage == nil) {
        _successImage = ({
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(80, 80 + SCREEN_HEIGHT, 625, 400)];
            imageView.image = [UIImage imageNamed:@"保存成功2.png"];
            imageView;
        });
    }
    return _successImage;
}

- (UILabel *)successID
{
    if (_successID == nil) {
        _successID = ({
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(135, 250, 300, 50)];
            label.font = [UIFont systemFontOfSize:20];
            label.textAlignment = NSTextAlignmentLeft;
            label;
        });
    }
    return _successID;
}

#pragma mark -  第二页的懒加载

- (UIImageView *)otherImage
{
    if (_otherImage == nil) {
        _otherImage = [[UIImageView alloc]initWithFrame:CGRectMake(20 + SCREEN_WIDTH, 20, SCREEN_WIDTH - 120, SCREEN_HEIGHT - 120)];
        _otherImage.userInteractionEnabled = YES;
        _otherImage.image = [UIImage imageNamed:@"down_08.png"];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeTheAddBtn)];
        [_otherImage addGestureRecognizer:tap];
    }
    return _otherImage;
}

- (UILabel *)otherOrderID
{
    if (_otherOrderID == nil) {
        _otherOrderID = [[UILabel alloc]initWithFrame:CGRectMake(35, 0, 400, 38)];
        _otherOrderID.text = @"订单号: 获取中..........";
    }
    return _otherOrderID;
}

- (UILabel *)otherName
{
    if (_otherName == nil) {
        _otherName = [[UILabel alloc]initWithFrame:CGRectMake(35, 38, 400, 38)];
        _otherName.text = @"姓名: 获取中..........";
    }
    return _otherName;
}

- (UILabel *)phone
{
    if (_phone == nil) {
        _phone = [[UILabel alloc]initWithFrame:CGRectMake(35, 76, 400, 38)];
        _phone.text = @"联系电话: 获取中..........";
    }
    return _phone;
}

- (UIView *)otherLine
{
    if (_otherLine == nil) {
        _otherLine = [[UIView alloc]initWithFrame:CGRectMake(35, 115, 824, 1)];
        _otherLine.backgroundColor = COLOR(170, 170, 170, 1);
    }
    return _otherLine;
}

- (UIButton *)addBtn
{
    if (_addBtn == nil) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addBtn.frame = CGRectMake(824, 20, 45, 45);
        [_addBtn setImage:[UIImage imageNamed:@"+_10.png"] forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(addBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

- (UIButton *)submit
{
    if (_submit == nil) {
        _submit = [UIButton buttonWithType:UIButtonTypeCustom];
        _submit.frame = CGRectMake(380, 500, 160, 50);
        [_submit setImage:[UIImage imageNamed:@"提交办理.png"] forState:UIControlStateNormal];
        [_submit addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submit;
}

- (UITableView *)otherTableView
{
    if (_otherTableView == nil) {
        _otherTableView = [[UITableView alloc]initWithFrame:CGRectMake(35, 170, CGRectGetWidth(self.otherImage.bounds) - 70, 225)];
        _otherTableView.rowHeight = 55;
        _otherTableView.delegate = self;
        _otherTableView.dataSource = self;
        _otherTableView.backgroundColor = [UIColor clearColor];
        _otherTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _otherTableView;
}

- (UIView *)listView
{
    if (_listView == nil) {
        _listView = ({
       UIView *listView = [[ListView alloc]initWithFrame:CGRectMake(540 + SCREEN_WIDTH, 75, 280, 500)];
            listView.hidden = YES;
            listView.layer.cornerRadius = 20;
            listView.clipsToBounds = YES;
            listView;
        });
    }
    return _listView;
}



@end
